﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EightQueueLib
{
    public class Queen
    {
        private int _row;
        private readonly int _col;
        private Queen _left;

        public Queen(int col, Queen left)
        {
            _row = 1;
            _col = col;
            _left = left;

            FindSolution();
        }

        public Queen Left
        {
            get { return _left; }
        }

        public int Col
        {
            get { return _col; }
        }

        public int Row
        {
            get { return _row; }
        }

        public bool CanAttack(int testRow, int testCol)
        {
            if (_row == testRow)
                return true;

            int colDiff = _col - testCol;
            if (_row + colDiff == testRow || _row - colDiff == testRow)
                return true;

            if (_left != null)
                return _left.CanAttack(testRow, testCol);
            else
                return false;
        }

        public bool FindSolution()
        {
            while (Left != null && Left.CanAttack(_row, _col))
            {
                if (!Advance())
                    return false;
            }

            return true;
        }

        public bool Advance()
        {
            if (_row < 8)
            {
                _row++;
                return FindSolution();
            }
            else
            {
                if (Left != null && !Left.Advance())
                {
                    return false;
                }

                _row = 1;
                return FindSolution();
            }
        }
    }
}
